const db = require('../db/index')
var _ = require('lodash')

// 获取树状结构
function getTreeResult(keyCategories, categories, type) {
    var result = [];
    for (idx in categories) {
        var cat = categories[idx];
        if (cat.cat_level == 0) {
            result.push(cat);
        } else {
            if (cat.cat_level >= type) continue;
            var parentCat = keyCategories[cat.cat_pid]
            if (!parentCat) continue;
            if (!parentCat.children) {
                parentCat['children'] = []
            }
            parentCat.children.push(cat);
        }
    }
    return result;
}
exports.getCategories = (req, res) => {
    // res.ResData("商品分类参数")
    var type = req.query.type
    var pagenum = req.query.pagenum //当前页码值
    var pagesize = req.query.pagesize //每页显示多少条数据
    var sql = "select * from sp_category"
    db.query(sql, (err, result) => {
        if (err) return res.ResDate(err)
            // console.log(result);
        var keyCategories = _.keyBy(result, 'cat_id')
            // console.log(keyCategories);
        if (!type) type = 3
        var resultdata = getTreeResult(keyCategories, result, type)
            // res.ResData(resultdata)
        if (pagenum && pagesize) {
            count = resultdata.length //总条数
            pagenum = parseInt(pagenum)
            pagesize = parseInt(pagesize)
            data = _.take(_.drop(resultdata, (pagenum - 1) * pagesize), pagesize)
                // console.log(data);
            data = {
                "total": count,
                "pagenum": pagenum,
                "pagesize": pagesize,
                "result": data
            }
            return res.ResData("获取参数列表成功!", 200, data)
        }
        res.ResData("获取参数列表成功!", 200, resultdata)
    })
}
exports.addcate = (req, res) => {
    // res.ResData("添加分类")
    // 1. 获取数据
    var cat_pid = req.body.cat_pid
    var cat_name = req.body.cat_name
    var cat_level = req.body.cat_level
        //2.检查分类名是否存在
    var sql = "select * from sp_category where cat_name=?"
    db.query(sql, cat_name, (err, result) => {
        if (err) return res.ResData("添加失败!")
        if (result.length > 0) return res.ResData("分类名已存在!")
            //3.添加数据
        var sql = "insert into sp_category (cat_name,cat_pid,cat_level)values(?,?,?)"
        db.query(sql, [cat_name, cat_pid, cat_level], (err, data) => {
            if (err) return res.ResData("添加失败!")
            var sql = "select * from sp_category where cat_name=?"
            db.query(sql, cat_name, (err, result) => {
                if (err) return res.ResData("获取分类信息失败!")
                res.ResData("添加分类成功", 201, {
                    "cat_id": result[0].cat_id,
                    "cat_name": result[0].cat_name,
                    "cat_pid": result[0].cat_pid,
                    "cat_level": result[0].cat_level
                })
            })
        })
    })
}
exports.searchcate = (req, res) => {
    // res.ResData('sad')
    var id = req.params.id;
    // 2.查询用户信息
    var sql = "select * from sp_category where cat_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("用户查询失败")
            // 3.返回结果
        if (result.length > 0) {
            res.ResData("用户查询成功", 200, {
                "id": result[0].cat_id,
                "cat_name": result[0].cat_name,
                "cat_pid": result[0].cat_pid,
                "cat_level": result[0].cat_level,
                // "email": result[0].mg_email
            })
        } else {
            res.ResData("用户查询失败")
        }

    })
}
exports.editcate = (req, res) => {
    // res.ResData("sdsa")
    var id = req.params.id;
    var name = req.body.cat_name;
    // console.log(req.body);
    var sql = "update sp_category set cat_name=? where cat_id=?"
    db.query(sql, [name, id], (err, result) => {
        if (err) return res.ResData("更新商品分类失败")
            // console.log(result);
            // if (result.affectedRows < 1)
            //     return res.ResData("更新失败")
        var sql = "select * from sp_category where cat_id=?"
        db.query(sql, id, (err, resResult) => {
            res.ResData("更新成功", 200, {
                    "id": resResult[0].cat_id,
                    "cat_name": resResult[0].cat_name,
                    "cat_pid": resResult[0].cat_pid,
                    "cat_level": resResult[0].cat_level,
                })
                // console.log(resResult);
        })
    })
}
exports.deletecate = (req, res) => {
    // res.ResData("sada")
    var id = req.params.id;
    var sql = "delete from sp_category where cat_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("删除失败")
        if (result.affectedRows != 1) return res.ResData("删除失败")
        res.ResData("删除成功", 200)
    })
}
exports.getattributes = (req, res) => {
    // res.ResData("sda")
    var id = req.params.id;
    // console.log(id);
    var sel = req.query.sel; //当前页码
    // console.log(sel);
    // var sql = 'select * from sp_attribute where attr_id=?';
    var sql = "SELECT * FROM sp_attribute WHERE cat_id = ? AND attr_sel = ? AND delete_time is NULL";
    db.query(sql, [id, sel], (err, result) => {
        if (err) return res.ResData(err)
            // console.log(result);
            // var keyCategories = _.keyBy(result, 'id');
            // console.log(keyCategories);
            // if (!type) type = 3;
            // var resultData = getTreeResult(keyCategories, result, type)
            // res.ResData(resultData)
            //参数判断
            // if (sel !== 'only' || sel !== 'many') {
            //     return res.ResData("参数错误")
            // }
            // 逻辑
        var data = [];
        for (idx in result) {
            data.push(result[idx])
        }
        // console.log(data);
        res.ResData("获取参数列表成功", 200, data)
            // if (sel == 'only' || sel == 'many') {
            //     return res.ResData("获取参数列表成功", 200, [{
            //         "attr_id ": result[0].attr_id,
            //         "attr_name": result[0].attr_name,
            //         "cat_id": result[0].cat_id,
            //         "attr_sel": result[0].attr_sel,
            //         "attr_write": result[0].attr_write,
            //         "attr_vals": result[0].attr_vals,
            //     }])

        // }
        // var data = [{
        //     "attr_id": result[0].attr_id,
        //     "attr_name": result[0].attr_name,
        //     "cat_id": result[0].cat_id,
        //     "attr_sel": result[0].attr_sel,
        //     "attr_write": result[0].attr_write,
        //     "attr_vals": result[0].attr_vals,
        // }]
        // return res.ResData("获取参数列表成功", 200, data)
        // res.ResData("获取参数列表成功", 200, resultData)
        // })
    })
}

exports.addattributes = (req, res) => {
    // res.ResData("sda")
    var id = req.params.id;
    var name = req.body.name;
    var sel = req.body.sel;
    var vals = req.body.vals;

    var sql1 = "SELECT * FROM sp_attribute WHERE attr_name = ?";

    db.query(sql1, name, (err, reslut) => {
            if (err) return res.ResData(err)
            var sql2 = "insert into sp_attribute(cat_id,attr_name,attr_sel,attr_vals)values(?,?,?,?)";
            db.query(sql2, [id, name, sel, vals], (err, reslut) => {
                if (err) return res.ResData(err)
                var sql3 = "SELECT * FROM sp_attribute WHERE attr_name = ?";
                db.query(sql3, [name], (err, data) => {
                    if (err) return res.ResData("创建失败!")
                    res.ResData("创建成功", 201, {
                        "attr_id": data[0].attr_id,
                        "attr_name": name,
                        "cat_id": id,
                        "attr_sel": sel,
                        "attr_write": data[0].attr_write,
                        "attr_vals": vals,
                    })
                    console.log(data);

                })
            })
        })
        // db.query(sql1, [id, sel], (err, reslut) => {
        //     if (err) return res.ResData(err)
        //     var sql = "insert into sp_attribute (attr_name,cat_id,attr_sel,attr_write,attr_vals) values(?,?,?,?,?)";

    // })

}